#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    char *buf;
    char *length;
    char buffer[256];

    if(argc < 5)
    {
        fprintf(stderr, "usage %s hostname port operation \"attr1;attr2;attr3;...\"\n", argv[0]);
        exit(0);
    }
    portno = atoi(argv[2]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd <0)
    {
        error("ERROR opening socket");
    }
    server = gethostbyname(argv[1]);

    if(server == NULL)
    {
        fprintf(stderr, "ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
    serv_addr.sin_port = htons(portno);
    if(connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <0) error("ERROR connection");
    printf("Connection established\n");

    bzero(buffer,255);
    strcpy(buffer, argv[3]);
    n = write(sockfd,buffer,strlen(buffer));
    if(n<0)error("ERROR writing to socket");
    n = read(sockfd,buffer,3);
    if(n<0)error("ERROR reading from socket");
    //bufor na dane do wyslania
    bzero(buffer,255);
    //najpierw wysyłamy długość danych
    sprintf(length, "%d", strlen(argv[4]));
    strcpy(buffer, "256");
    n = write(sockfd,buffer,strlen(buffer));
    if(n<0)error("ERROR writing to socket");
    n = read(sockfd,buffer,3);
    if(n<0)error("ERROR reading from socket");
    buf = malloc(strlen(argv[4])*sizeof(char)*2);
    //tutaj wstawiamy to co nas interesuje
    strcpy(buf, argv[4]);

    //piszemy do socketa
    n = write(sockfd,buf,strlen(buf));
    if(n<0)error("ERROR writing to socket");
    //potwierdzenie
    n = read(sockfd,buf,3);
    if(n<0)error("ERROR reading from socket");
    printf("Success\n");
    free(buf);
    close(sockfd);
    return 0;
}
